<?php

namespace app\admin\controller\select;


use app\common\controller\Backend;
use app\common\library\Feie;
use fast\Tree;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Config;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Model;
use app\common\library\RedisServer;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\select\Order
     */
    protected $model = null;
    protected $specsStatusList = [];
    protected $noNeedRight = ['getSpecs','selectInfoByCode'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\select\Order;
        $this->specsStatusList = $this->model->getSpecsStatusList();
        $this->view->assign("specsList", $this->model->getSpecsList());
        $this->view->assign("isFearQueryList", $this->model->getIsFearQueryList());
    }

    public function getSpecs(){
        $list = [
            ['name' => '单瓶'],
            ['name' => '整箱'],
            ['name' => '2瓶/箱'],
            ['name' => '4瓶/箱'],
            ['name' => '6瓶/箱'],
            ['name' => '12瓶/箱'],
            ['name' => '其他'],
        ];
        return json(['list' => $list, 'total' => count($list)]);
    }


    public function incodeorder()
    {
        if (false === $this->request->isAjax()) {
            $this->assign('year',date('Y'));
            return $this->view->fetch();
        }

        $batch_num_arr = array(
            '单瓶' => [
                'unit' => '瓶',
                'bottle_num' => 1
            ],
            '整箱' => [
                'unit' => '箱',
                'bottle_num' => 1
            ],
            '2瓶/箱' => [
                'unit' => '箱',
                'bottle_num' => 2
            ],
            '4瓶/箱' => [
                'unit' => '箱',
                'bottle_num' => 4
            ],
            '6瓶/箱' => [
                'unit' => '箱',
                'bottle_num' => 6
            ],
            '12瓶/箱' => [
                'unit' => '箱',
                'bottle_num' => 12
            ],
            '其他'   => [
                'unit' => '瓶',
                'bottle_num' => 1
            ],
        );
        $in_uname      = $this->request->param('out_name');
        $in_phone      = $this->request->param('out_phone');
        $note          = $this->request->param('note');
        $cate_id       = $this->request->param('cate_id');

        $params        = $this->request->post('row/a');
        $price         = $this->request->param('price',0);
        $is_fear_query  = $this->request->param('$is_fear_query',0);
        $insert_storage = json_decode($params['code_arr'],true);

        if(!$in_uname || !$insert_storage){
            $this->error('请完善信息');
        }

        $cate_model   = new \app\admin\model\select\Category();
        $category     = $cate_model->find($cate_id);

        $category_arr = $cate_model->where(['c_deleted'=>0])->column('c_id','c_title');

        Db::startTrans();
        //创建订单
        $order_model   = new \app\admin\model\select\Order();
        $order_number  = time().$this->auth->id;
        $order_insert  = array(
            'o_uid'          => $this->auth->id,
            'o_out_uname'    => '',
            'o_out_phone'    => '',
            'o_in_uname'     => '',
            'o_in_phone'     => '',
            'o_in_address'   => '',
            'o_order_number' => $order_number,
            'o_total_quantity' => count($insert_storage),
            'o_type' => 2,//1出库订单2入库订单
            'o_status' => 1,//1待出库订单2已出库订单3已完成0已取消
            'o_note' => $note,
            'o_create_time' => time(),
            'o_update_time' => time(),
            'o_enterprise_id' => $this->auth->es_id,
        );

        $order_insert['o_out_uname'] = $in_uname;
        $order_insert['o_out_phone'] =  $in_phone;

        $order_id = $order_model->insertGetId($order_insert);
        $order_info = $order_model->find($order_id);
        $storage_model = new \app\common\model\Storage();
        try {
            $now_year = date('Y', time());
            //处理订单创建逻辑
            foreach ($insert_storage as $k => $v) {
                //更改入库的状态  更改为已出库
                //成本价
                $purchase_price = 0;
                //绑定信息
                $update_storage_arr = [];

                if (isset($category_arr[$v['cate']])) {
                    $storage_cate_id   = $category_arr[$v['cate']];
                    $storage_cate_name = $v['cate'];
                } else {
                    $storage_cate_id   = $category['c_id'];
                    $storage_cate_name = $category['c_title'];
                }

                if (!$storage_cate_id || !$storage_cate_name) {
                    throw new Exception('请补充分类信息');
                }


                if (!isset($v['oi_specs']) || !$v['oi_specs']) {
                    $v['oi_specs'] = '单瓶';
                }

                $insert = [
                    'oi_enterprise_id' => $this->auth->es_id,
                    'oi_order_id' => $order_info['o_id'],
                    'oi_number' => $order_info['o_order_number'],
                    'oi_cate_id' => $storage_cate_id,
                    'oi_cate_name' => $storage_cate_name,
                    'oi_specs' => $v['oi_specs'],
                    'oi_price' => $v['price']??$price,
                    'oi_purchase_price' => $purchase_price,
                    'oi_num' => 1,
                    'oi_date' => $v['oi_date'],
                    'oi_batch' => $v['oi_batch'],
                    'oi_code' => $v['oi_code'],
                    'oi_is_fear_query' => $is_fear_query,
                    'oi_user_id' => $this->auth->id,
                    'oi_user_name' => $in_uname,
                    'oi_user_phone' => $in_phone,
                    'oi_warehouse' => 2,
                    'oi_surplus_num' => 1,
                    'oi_year' => $v['oi_year'] ?? $now_year,
                    'oi_unit' => $batch_num_arr[$v['oi_specs']]['unit'],
                    'oi_bottle_code' => $v['oi_bottle_code'],
                    'oi_bottle_num' => $batch_num_arr[$v['oi_specs']]['bottle_num'],
                    'oi_update_storage' => $update_storage_arr,
                    'oi_create_time' => time(),
                    'oi_update_time' => time(),
                ];

                $insert_id = $storage_model->insertGetId($insert);

            }
            Db::commit();
            $this->success('入库成功');
        }catch ( Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    public function outcodeorder()
    {
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }

        $batch_num_arr = array(
            '单瓶' => [
                'unit' => '瓶',
                'bottle_num' => 1
            ],
            '整箱' => [
                'unit' => '箱',
                'bottle_num' => 1
            ],
            '2瓶/箱' => [
                'unit' => '箱',
                'bottle_num' => 2
            ],
            '4瓶/箱' => [
                'unit' => '箱',
                'bottle_num' => 4
            ],
            '6瓶/箱' => [
                'unit' => '箱',
                'bottle_num' => 6
            ],
            '12瓶/箱' => [
                'unit' => '箱',
                'bottle_num' => 12
            ],
            '其他'   => [
                'unit' => '瓶',
                'bottle_num' => 1
            ],
        );

        //  $data          = $_REQUEST;
        $in_uname      = $this->request->param('out_name');
        $in_phone      = $this->request->param('out_phone');
        $note          = $this->request->param('note');
        $cate_id       = $this->request->param('cate_id');
        $params        = $this->request->post('row/a');
        $price         = $this->request->param('price',0);
        $insert_storage = json_decode($params['code_arr'],true);

        if(!$in_uname || !$insert_storage){
            $this->error('请完善信息');
        }

        $cate_model = new \app\admin\model\select\Category();
        $category   = $cate_model->find($cate_id);

        $category_arr = $cate_model->where(['c_deleted'=>0])->column('c_id','c_title');


        Db::startTrans();
        //创建订单
        $order_model   = new \app\admin\model\select\Order();
        $order_number  = time().$this->auth->id;
        $order_insert  = array(
            'o_uid'          => $this->auth->id,
            'o_out_uname'    => '',
            'o_out_phone'    => '',
            'o_in_uname'     => '',
            'o_in_phone'     => '',
            'o_in_address'   => '',
            'o_order_number' => $order_number,
            'o_total_quantity' => count($insert_storage),
            'o_type' => 1,//1出库订单2入库订单
            'o_status' => 1,//1待出库订单2已出库订单3已完成0已取消
            'o_note' => $note,
            'o_create_time' => time(),
            'o_update_time' => time(),
            'o_enterprise_id' => $this->auth->es_id,
        );

        $order_insert['o_in_uname'] = $in_uname;
        $order_insert['o_in_phone'] =  $in_phone;

        $order_id = $order_model->insertGetId($order_insert);
        $order_info = $order_model->find($order_id);
        $storage_model = new \app\common\model\Storage();
        try {
            $now_year = date('Y', time());
            //处理订单创建逻辑
            foreach ($insert_storage as $k => $v) {
                //更改入库的状态  更改为已出库
                //成本价
                $purchase_price = 0;
                //绑定信息
                $update_storage_arr = [];

                if (isset($category_arr[$v['cate_name']])) {
                    $storage_cate_id   = $category_arr[$v['cate_name']];
                    $storage_cate_name = $v['cate_name'];
                } else {
                    $storage_cate_id   = $category['c_id'];
                    $storage_cate_name = $category['c_title'];
                }

                if (!$storage_cate_id || !$storage_cate_name) {
                    throw new Exception('请补充分类信息');
                }


                if (!isset($v['oi_specs']) || !$v['oi_specs']) {
                    $v['oi_specs'] = '单瓶';
                }


                    $s_where = array();
                    $s_where['oi_code'] = $v['oi_code'];
                    $s_where['oi_warehouse'] = 2;
                    $s_where['oi_surplus_num'] = ['>', 0];
                    $s_where['oi_cate_id'] = $storage_cate_id;
                    $s_where['oi_specs'] = $v['oi_specs'];
                    $s_where['oi_year'] = $v['oi_year'] ?? $now_year;
                    $s_where['oi_enterprise_id'] = $this->auth->es_id;
                    $s_where['oi_is_deleted'] = 0;
                    //查询入库的商品  物流码一样的
                    $nocode_where = $s_where;
                    $nocode_where['oi_bottle_code'] = '';
                    $s_nocode_list = $storage_model->where($nocode_where)->order('oi_create_time', 'ASC')->select();
                    $code_where = $s_where;
                    $code_where['oi_bottle_code'] = $v['oi_bottle_code'];
                    $s_code_list = $storage_model->where($code_where)->order('oi_create_time', 'ASC')->select();
                    $out_num = 1;
                    $s_list = array_merge($s_code_list, $s_nocode_list);
                    //处理数量  可能出现出不完的情况  需要一点点计算
                    $trade_update_arr = array();
                    if (!$s_list) {
                        throw new Exception('库存不足!');
                    }
                    foreach ($s_list as $val) {
                        if ($val['oi_surplus_num'] >= $out_num) {
                            $s_update = array(
                                'oi_surplus_num' => $val['oi_surplus_num'] - $out_num,
                            );
                            $val->save($s_update);
                            $trade_update_arr[$val['oi_id']] = $out_num;
                            $out_num = 0;
                        } else {
                            $s_update = array(
                                'oi_surplus_num' => 0,
                            );
                            $val->save($s_update);
                            $out_num = $out_num - $val['oi_surplus_num'];
                            $trade_update_arr[$val['oi_id']] = $val['oi_surplus_num'];
                        }

                        if ($out_num == 0) {

                            break;
                        }
                    }
                    //记录此出库订单使用了那些入库的商品及数量
                    $update_storage_arr = json_encode($trade_update_arr);


                $insert = [
                    'oi_enterprise_id' => $this->auth->es_id,
                    'oi_order_id' => $order_info['o_id'],
                    'oi_number' => $order_info['o_order_number'],
                    'oi_cate_id' => $storage_cate_id,
                    'oi_cate_name' => $storage_cate_name,
                    'oi_specs' => $v['oi_specs'],
                    'oi_price' => $v['price']??$price,
                    'oi_purchase_price' => $purchase_price,
                    'oi_num' => 1,
                    'oi_date' => $v['oi_date'],
                    'oi_batch' => $v['oi_batch'],
                    'oi_code' => $v['oi_code'],
                    //'oi_is_fear_query' => $is_fear_query,
                    'oi_user_id' => $this->auth->id,
                    'oi_user_name' => $in_uname,
                    'oi_user_phone' => $in_phone,
                    'oi_warehouse' => 1,
                    'oi_surplus_num' => 1,
                    'oi_year' => $v['oi_year'] ?? $now_year,
                    'oi_unit' => $batch_num_arr[$v['oi_specs']]['unit'],
                    'oi_bottle_code' => $v['oi_bottle_code'],
                    'oi_bottle_num' => $batch_num_arr[$v['oi_specs']]['bottle_num'],
                    'oi_update_storage' => $update_storage_arr,
                    'oi_create_time' => time(),
                    'oi_update_time' => time(),
                ];


                $insert['oi_purchase_price'] = $s_list[0]['oi_price'];
                $insert['oi_is_fear_query'] = $s_list[0]['oi_is_fear_query'];


                $insert_id = $storage_model->insertGetId($insert);


                //入库信息记录出库id 进行绑定
                foreach ($trade_update_arr as $kk => $vv) {
                    $storage = $storage_model->find($kk);
                    $oi_update_storage = json_decode($storage['oi_update_storage'], true);
                    if (isset($oi_update_storage[$insert_id])) {
                        $oi_update_storage[$insert_id] = $oi_update_storage[$insert_id] + $insert['oi_num'];
                    } else {
                        $oi_update_storage[$insert_id] = $insert['oi_num'];
                    }
                    //入库信息  绑定出库信息   一个入库记录可能有多个出库记录 所有需要补充  不能直接覆盖
                    $storage->oi_update_storage = json_encode($oi_update_storage);
                    $storage->save();
                }


            }
            Db::commit();
            $this->success('出库成功');
        }catch ( Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    //设置订单备注
    public function savenote(){
        $id = $this->request->param('id');
        if(false == $this->request->isPost()){
            $order = $this->model->find($id);
            $this->assign('row',$order);
            return $this->view->fetch();
        }

        $note = $this->request->param('note');
        $this->model->isUpdate(true)->save(['o_note'=>$note],['o_id'=>$id]);
        $this->success('设置成功');

    }


    public function createorder(){
        if (false === $this->request->isAjax()) {
            $type         = $this->request->param('type');
            $this->view->assign('type',$type);
            return $this->view->fetch();
        }
        $out_uname    = $this->request->param('out_name');
        $out_phone    = $this->request->param('out_phone');
        $storage_list = $this->request->param('list');
        $type         = $this->request->param('type',1);
        $storage_list = json_decode($storage_list,true);
        if(!$storage_list){
            $this->error('请添加产品信息');
        }

        Db::startTrans();

        try{
            $order_model = new \app\admin\model\select\Order();

            $note    = $this->request->param('note');

            $order_data = array(
                'o_uid'          => $this->auth->id,
                //'o_in_address'   => $address,
                'o_order_number' => time().rand(1000,9999).$this->auth->id,
                'o_total_quantity' => 0,
                'o_type' => $type,//1出库订单2入库订单
                'o_status' => 0,//1待出库订单2已出库订单3已完成0已取消
                'o_note' => $note,
               // 'o_field'=> json_encode($ansObj),
                'o_create_time' => time(),
                'o_update_time' => time(),
                'o_enterprise_id' => $this->auth->es_id,
                'o_backstage_create' => 1,//后台创建订单
            );

            if($type == 1){
                $order_data['o_in_uname'] = $out_uname;
                $order_data['o_in_phone'] = $out_phone;
            }else{
                $order_data['o_out_uname'] = $out_uname;
                $order_data['o_out_phone'] = $out_phone;
            }
            $order_id = $order_model->insertGetId($order_data);
            foreach ($storage_list as $v){
                if($v['category_id'] &&  $v['num'] && $v['price']){
                    $insert[] = [
                        'og_order_id' => $order_id,
                        'og_year'     => $v['year'],
                        'og_cate_id'  => $v['category_id'],
                        'og_specs'    => $v['spec'],
                        'og_num'      => $v['num'],
                        'og_price'    => $v['price'],
                        'og_create_time' => time(),
                    ];
                }
            }
            $order_goods_model = new \app\common\model\OrderGoods();;
            $order_goods_model->insertAll($insert);
        }catch (PDOException|Exception $e){
            Db::rollback();
            $this->error($e->getLine().','.$e->getMessage());
        }

        Db::commit();
//        //小票打印
//        $feie_server = new Feie;
//        $feie_server->printOrderInfo($order_id,$this->auth->es_id);
        $this->success('创建成功');


    }



    //合并订单
    public function mergeorder($ids = null){
        $type = $this->request->param('type');
        if(empty($ids)){
            $this->error('请选择需要合并的订单');
        }

        if(count($ids) <= 1){
            $this->error('请至少选择两个及以上的订单');
        }
        $storage_model = new \app\admin\model\select\Storage();
        $where['o_id']            = ['in',$ids];
        $where['o_type']          = $type;
        $where['o_enterprise_id'] = $this->auth->es_id; //1客户2供货商
        $where['o_is_deleted']    = 0;
        $order_list    = $this->model->where($where)->select();

        //查询出来第一条订单信息
        $first_order = $this->model->find($ids[0]);

        //以第一个订单的客户名称进行查询  对比订单数量
        if($type == 1){
            $where['o_in_uname']       = $order_list[0]['o_in_uname'];
        }else{
            $where['o_out_uname']      = $order_list[0]['o_out_uname'];
        }
        $order_count = $this->model->where($where)->count();
        if($order_count != count($order_list)){
            $this->error(($type==1?'客户':'供货商').'名称不一致,无法合并订单');
        }
        Db::startTrans();
        //以第一个订单为主 进行合并订单
        $order_info = $order_list[0];
        unset($order_list[0]);
        $merge_ids = array_column($order_list,'o_id');





        //出库信息绑定到第一个订单上面

        $update_order_record = [];

        foreach ($merge_ids as $order_id){
            $storage_where     = [];
            $storage_where['oi_order_id']    = ['in',$merge_ids];
            $storage_where['oi_is_deleted'] = 0;
            //记录修改的订单信息
            $storage_list = $storage_model->where($storage_where)->select();
            $update_order_record[$order_id] = [];
            foreach ($storage_list as $val){
                $update_order_record[$order_id][] = $val['oi_id'];
            }
        }



        //删除除了第一个订单之外的订单
        $order_where['o_id'] = ['in',$merge_ids];
        $order_ret = $this->model->update(['o_is_deleted'=>1,'o_note'=>'订单合并'],$order_where);

        $storage_ret = $storage_model->update(['oi_order_id'=>$order_info['o_id'],'oi_number'=>$order_info['o_order_number']],$storage_where);
        if($order_ret){
            //转账记录绑定到第一个订单上面
            $account_record_model   = new \app\admin\model\account\Record();
            $account_record_where['oar_order_id']     = ['in',$merge_ids];
            $account_record_where['oar_type']         = 1;
            $account_record_where['oar_is_deleted']   = 0;
            $account_list = $account_record_model->where($account_record_where)->select();
            $update_account_record = [];
            foreach ($account_list as $val){
                $update_account_record[$val['oar_order_id']][] = $val['oar_id'];
            }
            $account_record_model->update(['oar_order_id'=>$order_info['o_id']],$account_record_where);

            //处理待出库待入库合并
            $order_goods_model = new \app\common\model\OrderGoods();
            $goods_record_where['og_order_id'] = ['in',$merge_ids];
            $goods_record_where['og_is_deleted'] = 0;
            $goods_list        = $order_goods_model->where($goods_record_where)->select();
            $update_goods_record = [];
            foreach ($goods_list as $val){
                $update_goods_record[$val['og_order_id']][] = $val['og_id'];
            }
            $order_goods_model->update(['og_order_id'=>$order_info['o_id']],$goods_record_where);

            //查询合并订单是否带有出入库信息  如果有  修改订单状态未已入库/已出库
            $storage_count = $storage_model->where($storage_where)->count();
            $order_count   = $storage_model->where(['oi_order_id'=>$order_info['o_id']])->count();
            if(($storage_count+$order_count) > 0 ){
                $update = [
                    'o_status' => 1
                ];
                $this->model->update($update,['o_id'=>$order_info['o_id']]);
            }

            //处理出入库状态是否已结款 获取订单总金额  对比 收付款记录对比
            $account_record_model->saveOrderSettled($order_info['o_id']);

            //记录合并订单和合并转账记录
            $merge_record_model = new \app\admin\model\select\MergeRecord();
            $insert             = [
                'mor_final_order_id' => $order_info['o_id'],
                'mor_merge_info'     => json_encode($update_order_record),
                'mor_merge_account'  => json_encode($update_account_record),
                'mor_merge_goods'  => json_encode($update_goods_record),
                'mor_create_time'    => time(),
            ];
            $merge_record_model->insert($insert);


            Db::commit();
            $this->success('合并成功');
        }else{
            Db::rollback();
            $this->error('合并失败');
        }
    }

    //撤回合并
    public function callbackmerge($ids){
        //$order_id = $this->request->param('id');
        $order_id = $ids;
        $merge_record_model = new \app\admin\model\select\MergeRecord();
        $account_record_model = new \app\admin\model\account\Record();
        $storage_model      = new \app\common\model\Storage();
        $row      = $merge_record_model
            ->where(['mor_final_order_id'=>$order_id,'mor_is_deleted'=>0])
            ->order('mor_create_time','DESC')
            ->find();

        if(!$row){
            $this->error('暂无合并信息');
        }

        Db::startTrans();

        try{
            //处理订单信息回退
            $order_info = json_decode($row['mor_merge_info'],true);
            foreach ($order_info as $order_id => $storage_arr){
                //删除订单回退
                $order = $this->model->find($order_id);
                $order->o_is_deleted = 0;
                $order->save();

                if($storage_arr){
                    $storage_model->update(['oi_order_id'=>$order_id,'oi_number'=>$order->o_order_number],['oi_id'=>['in',$storage_arr]]);
                }
            }

            //处理转账信息回退
            $account_info = json_decode($row['mor_merge_account'],true);
            foreach ($account_info as $order_id => $account_arr){
                $account_record_model->update(['oar_order_id'=>$order_id],['oar_id'=>['in',$account_arr]]);
            }

            $order_goods_model = new \app\common\model\OrderGoods();
            $order_goods_info  = json_decode($row['mor_merge_goods'],true);
            foreach ($order_goods_info as $order_id => $order_goods_arr){
                $order_goods_model->update(['og_order_id'=>$order_id],['og_id'=>['in',$order_goods_arr]]);
            }


            //删除合并记录
            $row->mor_is_deleted = 1;
            $row->save();
            //处理出入库状态是否已结款 获取订单总金额  对比 收付款记录对比
            $account_record_model->saveOrderSettled($ids);
        }catch(Exception|PDOException $e){
            DB::rollback();

            $this->error('回退失败');
        }

        Db::commit();
        $this->success('回退成功');
    }

    /**
     * 导入出库单
     */
    public function importorder(){
        if (false === $this->request->isAjax()) {
            $type      = $this->request->param('type');
            $this->view->assign('type',$type);
            return $this->view->fetch();
        }

        $type          = $this->request->param('type',1);

        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = array(
            '物流码' => 'oi_code',
            '瓶码' => 'oi_bottle_code',
            '生产日期' => 'oi_date',
            '批次' => 'oi_batch',
            '年份' => 'oi_year',
            '品类' => 'cate_name',
            '价格' => 'oi_price',
            '规格' => 'oi_specs',
        );

        //加载文件
        $insert_storage = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
                    }
                }
                if ($row && $row['oi_code']) {
                    $insert_storage[] = $row;
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert_storage) {
            $this->error(__('No rows were updated'));
        }

        $batch_num_arr = array(
            '单瓶' => [
                'unit' => '瓶',
                'bottle_num' => 1
            ],
            '整箱' => [
                'unit' => '箱',
                'bottle_num' => 1
            ],
            '2瓶/箱' => [
                'unit' => '箱',
                'bottle_num' => 2
            ],
            '4瓶/箱' => [
                'unit' => '箱',
                'bottle_num' => 4
            ],
            '6瓶/箱' => [
                'unit' => '箱',
                'bottle_num' => 6
            ],
            '12瓶/箱' => [
                'unit' => '箱',
                'bottle_num' => 12
            ],
            '其他'   => [
                'unit' => '瓶',
                'bottle_num' => 1
            ],
        );

      //  $data          = $_REQUEST;
        $in_uname      = $this->request->param('in_uname');
        $in_phone      = $this->request->param('in_phone');
        $note          = $this->request->param('note');
        $cate_id       = $this->request->param('cate_id');
        $is_fear_query = $this->request->param('is_fear_query');
        $price         = $this->request->param('price',0);

        $cate_model = new \app\admin\model\select\Category();
        $category   = $cate_model->find($cate_id);

        Db::startTrans();
        //创建订单
        $order_model   = new \app\admin\model\select\Order();
        $order_number  = time().$this->auth->id;
        $order_insert  = array(
            'o_uid'          => $this->auth->id,
            'o_out_uname'    => '',
            'o_out_phone'    => '',
            'o_in_uname'     => '',
            'o_in_phone'     => '',
            'o_in_address'   => '',
            'o_order_number' => $order_number,
            'o_total_quantity' => count($insert_storage),
            'o_type' => $type,//1出库订单2入库订单
            'o_status' => 1,//1待出库订单2已出库订单3已完成0已取消
            'o_note' => $note,
            'o_create_time' => time(),
            'o_update_time' => time(),
            'o_enterprise_id' => $this->auth->es_id,
        );
        if($type == 1){
            $order_insert['o_in_uname'] = $in_uname;
            $order_insert['o_in_phone'] =  $in_phone;
        }else{
            $order_insert['o_out_uname'] = $in_uname;
            $order_insert['o_out_phone'] =  $in_phone;
        }
        $order_id = $order_model->insertGetId($order_insert);
        $order_info = $order_model->find($order_id);
        $storage_model = new \app\common\model\Storage();
        try {
            $now_year = date('Y',time());
            //处理订单创建逻辑
            foreach ($insert_storage as $k=>$v){
                //更改入库的状态  更改为已出库
                //成本价
                $purchase_price = 0;
                //绑定信息
                $update_storage_arr = [];

                $cateInfo = $cate_model->where(['c_title'=>$v['cate_name']])->find();
                if($cateInfo){
                    $storage_cate_id   = $cateInfo['c_id'];
                    $storage_cate_name = $cateInfo['c_title'];
                }else{
                    $storage_cate_id   = $category['c_id'];
                    $storage_cate_name = $category['c_title'];
                }

                if(!$storage_cate_id || !$storage_cate_name){
                    throw new Exception('请补充分类信息');
                }


                if(!isset($v['oi_specs']) || !$v['oi_specs']){
                    $v['oi_specs'] = '单瓶';
                }

                if ($type ==1){
                    $s_where   = array();
                    $s_where['oi_code']        = $v['oi_code'];
                    $s_where['oi_warehouse']   = 2;
                    $s_where['oi_surplus_num'] = ['>',0];
                    $s_where['oi_cate_id']     = $storage_cate_id;
                    $s_where['oi_specs']       = $v['oi_specs'];
                    $s_where['oi_year']        = $v['oi_year']??$now_year;
                    $s_where['oi_enterprise_id'] = $this->auth->es_id;
                    $s_where['oi_is_deleted']  = 0;
                    //查询入库的商品  物流码一样的
                    $nocode_where     = $s_where;
                    $nocode_where['oi_bottle_code']   =  '';
                    $s_nocode_list    = $storage_model->where($nocode_where)->order('oi_create_time','ASC')->select();
                    $code_where       = $s_where;
                    $code_where['oi_bottle_code']     = $v['oi_bottle_code'];
                    $s_code_list      = $storage_model->where($code_where)->order('oi_create_time','ASC')->select();
                    $out_num          = 1;
                    $s_list           = array_merge($s_code_list,$s_nocode_list);
                    //处理数量  可能出现出不完的情况  需要一点点计算
                    $trade_update_arr = array();
                    if(!$s_list){
                        throw new Exception('库存不足!');
                    }
                    foreach ($s_list as $val){
                        if($val['oi_surplus_num'] >= $out_num){
                            $s_update = array(
                                'oi_surplus_num' => $val['oi_surplus_num'] - $out_num,
                            );
                            $val->save($s_update);
                            $trade_update_arr[$val['oi_id']] = $out_num;
                            $out_num = 0;
                        }else{
                            $s_update = array(
                                'oi_surplus_num' => 0,
                            );
                            $val->save($s_update);
                            $out_num = $out_num - $val['oi_surplus_num'];
                            $trade_update_arr[$val['oi_id']] = $val['oi_surplus_num'];
                        }

                        if($out_num == 0){

                            break;
                        }
                    }
                    //记录此出库订单使用了那些入库的商品及数量
                    $update_storage_arr = json_encode($trade_update_arr);
                }

                $insert     = [
                    'oi_enterprise_id' => $this->auth->es_id,
                    'oi_order_id' => $order_info['o_id'],
                    'oi_number' => $order_info['o_order_number'],
                    'oi_cate_id' => $storage_cate_id,
                    'oi_cate_name' => $storage_cate_name,
                    'oi_specs' => $v['oi_specs'],
                    'oi_price' => $price,
                    'oi_purchase_price' => $purchase_price,
                    'oi_num' => 1,
                    'oi_date'        => $v['oi_date'],
                    'oi_batch'       => $v['oi_batch'],
                    'oi_code'        => $v['oi_code'],
                    'oi_is_fear_query' => $is_fear_query,
                    'oi_user_id'     => $this->auth->id,
                    'oi_user_name'   => $in_uname,
                    'oi_user_phone'  => $in_phone,
                    'oi_warehouse'   => $type,
                    'oi_surplus_num' => 1,
                    'oi_year' => $v['oi_year']??$now_year,
                    'oi_unit' => $batch_num_arr[$v['oi_specs']]['unit'],
                    'oi_bottle_code'  => $v['oi_bottle_code'],
                    'oi_bottle_num'   => $batch_num_arr[$v['oi_specs']]['bottle_num'],
                    'oi_update_storage' => $update_storage_arr,
                    'oi_create_time'    => time(),
                    'oi_update_time'    => time(),
                ];

                if($type == 1){
                    $insert['oi_purchase_price'] =  $s_list[0]['oi_price'];
                    $insert['oi_is_fear_query']  =  $s_list[0]['oi_is_fear_query'];
                }

                $insert_id = $storage_model->insertGetId($insert);

                if ($type ==1){
                    //入库信息记录出库id 进行绑定
                    foreach($trade_update_arr as $kk=>$vv){
                        $storage = $storage_model->find($kk);
                        $oi_update_storage = json_decode($storage['oi_update_storage'],true);
                        if(isset($oi_update_storage[$insert_id])){
                            $oi_update_storage[$insert_id] =  $oi_update_storage[$insert_id] + $insert['oi_num'];
                        }else{
                            $oi_update_storage[$insert_id] =  $insert['oi_num'];
                        }
                        //入库信息  绑定出库信息   一个入库记录可能有多个出库记录 所有需要补充  不能直接覆盖
                        $storage->oi_update_storage =  json_encode($oi_update_storage);
                        $storage->save();
                    }
                }

            }
        } catch (PDOException $exception) {
            Db::rollback();
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success();

    }

    /**
     * 后台出库
     * @return mixed
     *
     */
    public function outwarehouse(){
        if (false === $this->request->isAjax()) {
            $ids        = $this->request->param('ids');
            $type       = $this->request->param('type');
//        $id_arr   = plum_explode($ids);
            if(empty($ids)){
                $this->error('请选择需要出库的数据');
            }
            $stroage_model = new \app\common\model\Storage;
            $where['oi_warehouse']     = 2;
            $where['oi_is_deleted']    = 0;
            $where['oi_surplus_num']   = ['>',0];
            if($type == 'order'){
                $where['oi_order_id']      = ['in',$ids];
            }else{
                $where['oi_id']      = ['in',$ids];
            }
            $stroage_list  = $stroage_model->getStorageInfoListBysYear($where);
            if(!$stroage_list){
                $this->error('库存不足');
            }
            $where['oi_is_deleted'] = 0;
            $stroage_count = $stroage_model->where($where)->count();
            if($type == 'storage'){
                if($stroage_count < count(explode(',',$ids))){
                    $this->error('库存不足');
                }
            }

            foreach ($stroage_list as &$val){
                $val['specs_status'] = $this->specsStatusList[$val['oi_specs']];
                $val['is_fear_query_text'] = $val['oi_is_fear_query'] == 1?'怕查':'不怕查';
            }
            $this->view->assign('storage_list',$stroage_list);
            $this->view->assign('ids',$ids);
            $this->view->assign('type',$type);
            return $this->view->fetch();
        }


        $ids      = $this->request->param('ids');
        if(empty($ids)){
            $this->error('请选择需要修改的数据');
        }
        $data          = $_REQUEST;
        $in_uname      = $data['in_uname'];
        $in_phone      = $data['in_phone'];
        $type          = $data['type'];
        unset($data['in_uname'],$data['in_phone'],$data['type']);
       // $data     = array_column($data,'value','name');

        $stroage_model = new \app\common\model\Storage();
        $where                       = [];
        $where['oi_warehouse']     = 2;
        $where['oi_is_deleted']    = 0;
        $where['oi_surplus_num']    = ['>',0];
        if($type == 'order'){
            $where['oi_order_id']      = ['in',$ids];
        }else{
            $where['oi_id']      = ['in',$ids];
        }
        //$where[]       = array('name'=>"oi_number",'oper'=>'in','value'=>['16659892693790','16659892173790','16659891563790','16659891423790','16659897893790']);
        $stroage_list  = $stroage_model->where($where)->select();
        $stroage_list = collection($stroage_list)->toArray();
        Db::startTrans();
        //创建订单
        $order_model   = new \app\admin\model\select\Order();
        $order_number  = time().$this->auth->id;
        $order_insert  = array(
            'o_uid'          => $this->auth->id,
            'o_out_uname'    => $this->auth->nickname,
            'o_out_phone'    => '',
            'o_in_uname'     => $in_uname,
            'o_in_phone'     => $in_phone,
            'o_in_address'   => '',
            'o_order_number' => $order_number,
            'o_total_quantity' => count($stroage_list),
            'o_type' => 1,//1出库订单2入库订单
            'o_status' => 1,//1待出库订单2已出库订单3已完成0已取消
            'o_note' => '',
            'o_create_time' => time(),
            'o_update_time' => time(),
            'o_enterprise_id' => $this->auth->es_id,
        );
        $order_id = $order_model->insertGetId($order_insert);
        foreach ($stroage_list as $val){
            if($val['oi_surplus_num'] == 0){
                Db::rollback();
                $this->error('库存不足');
            }
            //处理当前普茅出库
            $update = array(
                'oi_surplus_num' => 0
            );
            $stroage_model->where(['oi_id'=>$val['oi_id']])->update($update);
            //记录绑定出库信息
            $trade_update_arr = array();
            $trade_update_arr[$val['oi_id']] = $val['oi_surplus_num'];
            unset($val['oi_id']);
            $val['oi_order_id'] = $order_id;
            $val['oi_number'] = $order_number;
            $val['oi_purchase_price'] = $val['oi_price'];
            $val['oi_price'] = $data['out_price_'.$val['oi_year'].'_'.$val['oi_cate_id'].'_'.$this->specsStatusList[$val['oi_specs']].'_'.$val['oi_is_fear_query']];
            $val['oi_warehouse'] = 1;
            $val['oi_create_time'] = time();
            $val['oi_update_time'] = time();
            $val['oi_user_name'] = $in_uname;
            $val['oi_user_phone'] = $in_phone;
            // $val['oi_update_storage'] = '';
            $val['oi_num'] =  $val['oi_surplus_num'];
            $val['oi_surplus_num'] = 0; //剩余瓶数 = 1
            $val['oi_update_storage'] = json_encode($trade_update_arr);

            $insert_id = $stroage_model->insertGetId($val);


            //入库信息记录出库id 进行绑定
            foreach($trade_update_arr as $kk=>$vv){
                $storage = $stroage_model->find($kk);
                $oi_update_storage = json_decode($storage['oi_update_storage'],true);
                if(isset($oi_update_storage[$insert_id])){
                    $oi_update_storage[$insert_id] =  $oi_update_storage[$insert_id] + $val['oi_num'];
                }else{
                    $oi_update_storage[$insert_id] =  $val['oi_num'];
                }
                //入库信息  绑定出库信息   一个入库记录可能有多个出库记录 所有需要补充  不能直接覆盖
                $storage->oi_update_storage =  json_encode($oi_update_storage);
                $storage->save();
            }

        };
        Db::commit();
        $this->success('出库成功');
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function out(){
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        $ret = $this->index(1);
        return $ret;
    }


    public function in(){
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        $ret = $this->index(2);
        return $ret;
    }

    public function refundorder(){
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        //先查询表单信息
        $filter = $this->request->param('filter');
        $filter_arr = json_decode($filter,true);

        [$where, $sort, $order, $offset, $limit] = $this->buildparams();


        $request = $this->model->alias('order')
            ->join( 'admin a ','a.id = order.o_uid','left')
            ->where($where)
            ->where(['o_enterprise_id'=>$this->auth->es_id,'o_has_refund'=>1,'o_type'=>1])
            ->order($sort, $order)
            ->paginate($limit);




        $list = $request->items();
        $storage_info_model = new \app\common\model\Storage;
        $cate_model = new \app\admin\model\select\Category;
        $account_record_model = new \app\common\model\Accountrecord;
        foreach($list as $key=>$val){

            //循环该订单根据品类进行分组去重
            $storageList   = $storage_info_model
                ->where(['oi_refund_time'=>['<>',0],'oi_order_id'=>$val['o_id'],'oi_warehouse'=>1])
                ->group('oi_cate_name,oi_year,oi_price,oi_specs')
                ->select();
//            if ($storageList){
            $storage_list = array();
            $storage_str  = array();
            $storage_total = 0;
            $profit_total = 0;
            $order_money_total = 0;
            foreach ($storageList as $kk=>$vv){
                $num_list = $storage_info_model->where(['oi_refund_time'=>['<>',0],'oi_order_id'=>$val['o_id']
                    ,'oi_warehouse'=>1,'oi_cate_name'=>$vv['oi_cate_name'],'oi_price'=>$vv['oi_price'],'oi_year'=>$vv['oi_year'],'oi_specs'=>$vv['oi_specs']])
                    ->select();
                $storage_num = 0;
                $storage_profit_total = 0;
                foreach ($num_list as $vvv){
                    $storage_num += $vvv['oi_num'];
                    if($vvv['oi_purchase_price'] != 0 && $vvv['oi_price'] != 0){
                        $storage_profit_total += ($vvv['oi_price'] - $vvv['oi_purchase_price'])  * $vvv['oi_num'] * $vvv['oi_bottle_num'];
                    }
                }
                $storage_list[$kk]['oi_cate_name'] = $vv['oi_year'].'年'.$vv['oi_cate_name'].'('.$vv['oi_specs'].')';
                $storage_list[$kk]['price'] = $vv['oi_price'];
                $storage_list[$kk]['num'] = $storage_num;
                $storage_list[$kk]['total_price'] = $vv['oi_price'] * $storage_num * $vv['oi_bottle_num'];
                $storage_total += $storage_num;
                $profit_total += $storage_profit_total;
                $order_money_total += $storage_list[$kk]['total_price'];

                $storage_str[] = ($vv['oi_year']?$vv['oi_year'].'年'.$vv['oi_cate_name']:$vv['oi_cate_name']).'('.$vv['oi_specs'].')'.
                    ' : '.$storage_num.($vv['oi_price']?'单价:'.$vv['oi_price'].'合计：'. $storage_list[$kk]['total_price']:'');
            }

            $list[$key]['storage_total'] = $storage_total;
            $list[$key]['profit_total'] = $profit_total;
            $list[$key]['order_money_total'] = $order_money_total;
            $list[$key]['storage_list'] = $storage_str;


        }
        $result = ['total' => $request->total(), 'rows' => $list];
        return json($result);
    }

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index($order_type = 1)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        //先查询表单信息
        $filter = $this->request->param('filter');
        $filter_arr = json_decode($filter,true);

        [$where, $sort, $order, $offset, $limit] = $this->buildparams();

        if(isset($filter_arr['order_money'])){
            //嵌套查询  先查询订单总金额  在进行搜索查询
            $storage_model = new \app\common\model\Storage();
            $order_money_sql = $storage_model->where(['oi_warehouse'=>$order_type])->field('oi_order_id,sum(oi_price * oi_num * oi_bottle_num) as order_money')
                ->group('oi_order_id')
                ->buildSql();

            $request = Db::table($order_money_sql.'  tt')
                ->join( 'order order ','tt.oi_order_id = order.o_id','inner')
                ->join( 'admin a ','a.id = order.o_uid','left')
                ->where($where)
                ->where(['o_enterprise_id'=>$this->auth->es_id,'o_is_deleted'=>0,'o_type'=>$order_type])
                ->order($sort, $order)
                ->paginate($limit);
        }else{
            $request = $this->model->alias('order')
                ->join( 'admin a ','a.id = order.o_uid','left')
                ->where($where)
                ->where(['o_enterprise_id'=>$this->auth->es_id,'o_is_deleted'=>0,'o_type'=>$order_type])
                ->order($sort, $order)
                ->paginate($limit);
        }



        $list = $request->items();
        $storage_info_model = new \app\common\model\Storage;
        $cate_model = new \app\admin\model\select\Category;
        $account_record_model = new \app\common\model\Accountrecord;
        foreach($list as $key=>$val){

            //循环该订单根据品类进行分组去重
            $storageList   = $storage_info_model
                ->where(['oi_is_deleted'=>0,'oi_order_id'=>$val['o_id'],'oi_warehouse'=>$order_type])
                ->group('oi_cate_name,oi_year,oi_price,oi_specs,oi_is_fear_query')
                ->select();
//            if ($storageList){
            $storage_list = array();
            $storage_str  = array();
            $storage_total = 0;
            $profit_total = 0;
            $order_money_total = 0;
            foreach ($storageList as $kk=>$vv){
                $num_list = $storage_info_model->where(['oi_is_deleted'=>0,'oi_order_id'=>$val['o_id']
                    ,'oi_warehouse'=>$order_type,'oi_cate_name'=>$vv['oi_cate_name'],'oi_price'=>$vv['oi_price'],'oi_year'=>$vv['oi_year'],'oi_specs'=>$vv['oi_specs'],'oi_is_fear_query'=>$vv['oi_is_fear_query']])
                //->field('SUM(oi_num) as num,sum((oi_price - oi_purchase_price)  * oi_num * oi_bottle_num) as profit_total')
                ->select();
                $storage_num = 0;
                $storage_profit_total = 0;
                foreach ($num_list as $vvv){
                    $storage_num += $vvv['oi_num'];
                    if($vvv['oi_purchase_price'] != 0 && $vvv['oi_price'] != 0){
                        $storage_profit_total += ($vvv['oi_price'] - $vvv['oi_purchase_price'])  * $vvv['oi_num'] * $vvv['oi_bottle_num'];
                    }
                }
                $storage_list[$kk]['oi_cate_name'] = $vv['oi_year'].'年'.$vv['oi_cate_name'].'('.$vv['oi_specs'].')';
                $storage_list[$kk]['price'] = $vv['oi_price'];
                $storage_list[$kk]['num'] = $storage_num;
                $storage_list[$kk]['total_price'] = $vv['oi_price'] * $storage_num * $vv['oi_bottle_num'];
                $storage_total += $storage_num;
                $profit_total  += $storage_profit_total;
                $order_money_total += $storage_list[$kk]['total_price'];

                $is_fear_query_text = $vv['oi_is_fear_query'] == 1?'怕查':'不怕查';
                $storage_str[] = ($vv['oi_year']?$vv['oi_year'].'年'.$vv['oi_cate_name']:$vv['oi_cate_name']).'('.$vv['oi_specs'].'|'.$is_fear_query_text.')'.
                    ' : '.$storage_num.($vv['oi_price']?'单价:'.$vv['oi_price'].'合计：'. $storage_list[$kk]['total_price']:'');



            }

            $list[$key]['storage_total'] = bcmul($storage_total , 1 , 2);
            $list[$key]['profit_total'] = bcmul($profit_total , 1 , 2);
            $list[$key]['order_money_total'] = bcmul($order_money_total , 1 , 2);
            $list[$key]['storage_list'] = $storage_str;


            //查询待出入库信息
            $out_storage_list  = [];
            $order_goods_model = new \app\common\model\OrderGoods();
            $storage_info      = $order_goods_model->where(['og_order_id'=>$val['o_id']])->select();
            foreach ($storage_info as $vv){
                $cate  = $cate_model->find($vv['og_cate_id']);
                $out_storage_list[] =  ($vv['og_year']?$vv['og_year'].'年'.$cate['c_title']:$cate['c_title']).(isset($vv['og_specs'])?'('.$vv['og_specs'].')':'').' : '.$vv['og_num'].'(￥'.$vv['og_price'].')';
            }



            $list[$key]['out_storage_list'] = $out_storage_list;
            $list[$key]['field'] = json_decode($val['o_field'],true);

            //查询清账信息 和转账记录
            $where = ['oar_order_id'=>$val['o_id'],'oar_type'=>1,'oar_is_deleted'=>0];
            $account_record_money_total = $account_record_model->where($where)->field('sum(oar_money) as total')->find();
            $list[$key]['account_record_money_total'] = $account_record_money_total['total']?$account_record_money_total['total']:0;
            $account_record             = $account_record_model->where($where)->select();
            $account_record_str         = [];
            foreach ($account_record as $vv){
                $account_record_str[]   = '转出账户:'.$vv['oar_out_account_title'].';转入账户:'.$vv['oar_in_account_title'].';金额:'.$vv['oar_money']."</br>";
            }
            $list[$key]['account_record_str'] = $account_record_str;
        }
        $result = ['total' => $request->total(), 'rows' => $list];
        return json($result);
    }


    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {

        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $params['o_es_id'] =  $this->auth->es_id;
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            if($row['o_type'] == 1){
                $row['in_uname'] = $row['o_in_uname'];
                $row['in_phone'] = $row['o_in_phone'];
            }else{
                $row['in_uname'] = $row['o_out_uname'];
                $row['in_phone'] = $row['o_out_phone'];
            }
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }

            $id       = $this->request->param('id');
            $type       = $this->request->param('type');
            $in_name  = $this->request->param('in_name');
            $in_phone = $this->request->param('in_phone');


            if($type == 1){
                $update = array(
                    'o_in_uname' => $in_name,
                    'o_in_phone' => $in_phone,
                );
            }else{
                $update = array(
                    'o_out_uname' => $in_name,
                    'o_out_phone' => $in_phone
                );
            }
            $result = $this->model->update($update,['o_id'=>$row['o_id']]);
            if($result){
                //还需要修改订单的客户信息
                $storage_model = new \app\admin\model\select\Storage();
                $update        = array(
                    'oi_user_name' => $in_name,
                    'oi_user_phone' => $in_phone,
                );
                $storage_model->update($update,['oi_order_id'=>$id]);
            }else{
                Throw new Exception('修改失败');
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
 
        $this->success();
    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;

        Db::startTrans();
        try {
            //处理删除逻辑
            foreach ($list as $item) {
                //判断如果是出库订单  需要回退
                if($item->o_type == 1){

                    $this->deletedFallBack($item->o_order_number);
                }

                $count += $item->save(['o_is_deleted'=>1]);





            }

            //删除入库信息
            $storage_info_model = new \app\admin\model\select\Storage();
            //删除绑定的出入库信息
            $update             = array(
                'oi_is_deleted'  => 1
            );
            $storage_info_model->isUpdate()->save($update,['oi_order_id'=>['in' , $ids]]);
            //删除绑定的转账记录
            $account_model = new \app\admin\model\account\Record();
            $update             = array(
                'oar_is_deleted'  => 1
            );
            $account_model->isUpdate()->save($update,['oar_order_id'=>['in' , $ids]]);
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }


    /**
     * 取消订单
     */
    public function cancelOrder($ids = null){
        Db::startTrans();
        try{
            if(!$ids) {
                throw new Exception('状态错误，请联系管理员处理，删除');
            }
            $order       = $this->model->find($ids);
            //判断如果是出库订单  需要回退
            if($order['o_type'] == 1){
                $this->deletedFallBack($order['o_order_number']);
            }
            //删除订单
            $update      = array(
                'o_status' => -1, //已取消
                'o_has_refund' => 1 //订单有退库
            );
            $order_res = $order->save($update);
            if(!$order_res) {
                throw new Exception('取消失败');
            }
            //删除入库信息
            $storage_info_model = new \app\common\model\Storage();
            $update             = array(
                'oi_is_deleted'  => 1,
                'oi_refund_time' => time()
            );
            $where['oi_order_id']     = array( '=' , $ids );
            $where['oi_refund_time']  = array( '=' , 0 );
            $where['oi_is_deleted']   = array( '=' , 0 );
            $storage_info_model->update($update,$where);

            Db::commit();
            $this->success('取消成功');
        } catch ( Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }

    }




    public function ajaxShowTrade($ids = null){
        if(empty($ids)){
            $this->error('请选择需要打印的订单');
        }
        $type = $this->request->param('type',1);

        $content = $type==1?Config::get('out_print_content'):Config::get('in_print_content');

        $order_model = new \app\admin\model\select\Order;
        $storage_info_model = new \app\admin\model\select\Storage();
        $order_info = $order_model->find(['o_id'=>['in',$ids]]);


        if($order_info['o_type'] == 1){
            $order_name = $order_info['o_in_uname'];
            $order_phone = $order_info['o_in_phone'];
        }else{
            $order_name = $order_info['o_out_uname'];
            $order_phone = $order_info['o_out_phone'];
        }


        //获取操作人
        $admin_model = new \app\admin\model\Admin();
        $admin       = $admin_model->find($order_info['o_uid']);

        $storage_info   = $storage_info_model
            ->where(['oi_order_id'=>['in',$ids]])
            ->field('*,sum(oi_num) as total')
            ->group('oi_cate_id,oi_year,oi_price,oi_specs')
            ->select();


        $list = array();
        $new_list    = array();
        $cate_model = new \app\admin\model\select\Category;

        foreach ($storage_info as $key=>$val){
            //查询当前分类所包含的order_id
//            $where   = array();
//            $where[] = array('name' => 'oi_cate_id', 'oper' => '=', 'value' => $val['oi_cate_id']);
//            $where[] = array('name' => 'oi_order_id', 'oper' => 'in', 'value' => $id_arr);
//            $order_list = $order_model->getList($where,0,0,array());
//            $order_arr  =  array_column($order_list,'o_id');
            $where = array();
            $where['oi_order_id'] = array('in',$ids);
            $where['oi_cate_id'] = $val['oi_cate_id'];
            $where['oi_specs'] = $val['oi_specs'];
            $where['oi_year'] = $val['oi_year'];
            $where['oi_price'] = $val['oi_price'];
            $list [$key]['cate_id']    = $val['oi_cate_id'];
            $list [$key]['cate_name']  = $val['oi_cate_name'];
            $cate = $cate_model->find($val['oi_cate_id']);
            $list [$key]['oi_specs'] = $val['oi_specs'];
            $list [$key]['oi_price'] = $val['oi_price'];
            $list [$key]['oi_num'] = $val['oi_num'];
            $list [$key]['oi_bottle_num'] = $val['oi_bottle_num'];
            $list [$key]['oi_purchase_price'] = $val['oi_purchase_price'];
            $list [$key]['oi_year']  = $val['oi_year'];
            $list [$key]['oi_unit']  = $val['oi_unit'];
            $list [$key]['total']      = $val['total'];
            $handle_list = $storage_info_model->where($where)->select();

            foreach ($handle_list as $kk=>$vv){
                for($i = 1 ; $i<=$vv['oi_num']; $i++){
                    $new_list[] = array(
                        'code'  => $vv['oi_code'],
                        'batch' => $vv['oi_batch'],
                        'date' => $vv['oi_date'],
                        'bottle_code' => $vv['oi_bottle_code'],
                    );
                }
            }
        }
        $codeList1     = array();
        $codeList2     = array();
        //plum_msg_dump($new_list,1);

        for($i=0;$i<=count($new_list);$i=$i+2){
            if(isset($new_list[$i])){
                $codeList1[] = $new_list[$i];
            }
            if(isset($new_list[$i+1])){
                $codeList2[] = $new_list[$i+1];
            }

        }

        $data = array(
            'cateList'        => $list,
            'o_update_time' => date('Y/m/d',$order_info['o_update_time']),
            'out_name' => $order_name,
            'out_phone' => $order_phone,
            'codeList1' => $codeList1,
            'codeList2' => $codeList2,
            'admin_name' => $admin['nickname'],
        );
//        $field = json_decode($order_info['o_field'],true);
//        $data['field']  = $field;

        //plum_msg_dump($data,1);



//        $type        = $this->request->param('type','print');
//        if($type == 'print'){
        $content     = $this->_str_replace_tag($content,$data,$type);
        $this->view->assign('content', $content);
//        }else{
//            $PHPExcel  = new App_Plugin_PHPExcel_PHPExcelPlugin();
//            $PHPExcel->_excel_trade($data);
//        }
        return $this->view->fetch();
    }


    public function _str_replace_tag($template,$orderRow,$type = 1){
        $tbody    = explode('<tbody>',$template);
        $endTbody = explode('</tbody>',$tbody[1]);
        $table    = $endTbody[0];
        $t_arr    = array();
        $totalMoney = 0;
        foreach($orderRow['cateList'] as $key => $val){
//            foreach ($val['list'] as $v){
//
//            }
            $temp = $table;
            $ret = str_replace('{spm}',$val['cate_name'],$temp);
            $ret = str_replace('{gg}',$val['oi_specs'],$ret);
            $ret = str_replace('{dw}',$val['oi_unit'],$ret);
            $ret = str_replace('{dj}',$val['oi_price'],$ret);
            $ret = str_replace('{sl}',$val['total'],$ret);
            $ret = str_replace('{hj}',$val['oi_price'] * $val['total'] * $val['oi_bottle_num'],$ret);
            $t_arr[] = $ret;
            $totalMoney += $val['oi_price'] * $val['total'] * $val['oi_bottle_num'];
        }
        $tbody    = explode('<tbody1>',$template);
        $endTbody = explode('</tbody1>',$tbody[1]);
        $table    = $endTbody[0];
        $code_arr = array();
        foreach ($orderRow['codeList1'] as $key=>$val){
            $temp = $table;
            $ret = str_replace('{date1}',$val['date'],$temp);
            $ret = str_replace('{batch1}',$val['batch'],$ret);
            $ret = str_replace('{code1}',$val['code'],$ret);
            $ret = str_replace('{bottle_code1}',$val['bottle_code'],$ret);
            $ret = str_replace('{date2}',isset($orderRow['codeList2'][$key]['date'])?$orderRow['codeList2'][$key]['date']:'',$ret);
            $ret = str_replace('{batch2}',isset($orderRow['codeList2'][$key]['batch'])?$orderRow['codeList2'][$key]['batch']:'',$ret);
            $ret = str_replace('{code2}',isset($orderRow['codeList2'][$key]['code'])?$orderRow['codeList2'][$key]['code']:'',$ret);
            $ret = str_replace('{bottle_code2}',isset($orderRow['codeList2'][$key]['bottle_code'])?$orderRow['codeList2'][$key]['bottle_code']:'',$ret);
            $code_arr[] = $ret;
        }
        $template = str_replace('{totalMoney}',$totalMoney,$template);
        $template = str_replace('{riqi}',$orderRow['o_update_time'],$template);
        if($type == 1){
            $template = str_replace('{xiaoshou}',$orderRow['admin_name'],$template);
        }
        $template = str_replace('{kehumingcheng}',$orderRow['out_name'],$template);
        $template = str_replace('{kehudianhua}',$orderRow['out_phone'],$template);
        $template = preg_replace('/<tbody>(.*?)<\/tbody>/is', implode('',$t_arr), $template);
        $template = preg_replace('/<tbody1>(.*?)<\/tbody1>/is', implode('',$code_arr), $template);
        return $template;
    }

    //根据物流码查询相关入库信息
    public function selectInfoByCode(){
        $code = $this->request->param('code');

        $storage_model = new \app\admin\model\select\Storage();
        $where['oi_code'] = $code;
        $where['oi_enterprise_id'] = $this->auth->es_id;
        $where['oi_warehouse'] = 2;
        $where['oi_is_deleted']   = 0;
        $where['oi_surplus_num'] = ['>',0];
        $row     = $storage_model->alias('info')
            ->join('category cate' , 'info.oi_cate_id = cate.c_id')
            ->where($where)->find();
        if(!$row){
            $this->error('库存不存在此物流码');
        }
        $data    = array(
            'cate_id' => $row['oi_cate_id'],
            'cate_name' => $row['c_title'],
            'specs' => $row['oi_specs'],
            'year' => $row['oi_year'],
            'date'  => $row['oi_date'],
            'price'  => $row['oi_price'],
            'batch' => $row['oi_batch'],
            'bottle_code' => $row['oi_bottle_code'],
        );
        $this->success('查询成功' , '',$data);
    }

}
